package sseGameApps.controller.mdkbr.login;

import java.util.Date;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;

import sseGameApps.service.mdkbr.MdKbrAuthService;

public class LoginController extends Controller {

    private MdKbrAuthService service = new MdKbrAuthService();

    @Override
    public Navigation run() throws Exception {
        if (!validate()) {
            return forward(basePath);
        }

        sessionScope("userId", asString("userId"));

        if ("".equals(asString("firstLogin"))) {
            if (!service.firstLogin(
                asString("userId"),
                asString("passWord"),
                new Date(System.currentTimeMillis()))) {
                Validators v = new Validators(request);
                v.getErrors().put("passWord", "ユーザＩＤまたはパスワードが不正です");
                return forward(basePath);
            }
            return redirect("/mdkbr/main/?userId=" + asString("userId"));

        } else {

            int returnCode = service.registUser(
                asString("userId"),
                asString("passWord"),
                new Date(System.currentTimeMillis()));

            if (returnCode == 1) {
                Validators v = new Validators(request);
                v.getErrors().put("userId", "このユーザＩＤは登録済です");
                return forward(basePath);
            }
            return redirect("/mdkbr/regist/?userId=" + asString("userId") + "&firstLogin=1");

        }

    }

    protected boolean validate() {
        Validators v = new Validators(request);
        v.add("userId", v.required(),v.regexp("^[\\w]+$"));
        v.add("passWord", v.required(),v.regexp("^[\\w]+$"));
        return v.validate();
    }
}
